import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable
} from "@ant-design/pro-components";
import React, {useRef, useState} from "react";
import {Button, Form} from "antd";
import {EditOutlined, PlusOutlined, SettingFilled, TeamOutlined} from "@ant-design/icons";
import {globalApi, globalLoadTableApi, globalLoadTableApiCode, handleGloblApi} from "@/services/admin-api/globalApi";
import {useAccess} from "umi";

type User = {
  usId: number;
  usUuid: string;
  usNickName: string;
  usRealName: string;
  usLoginName: string;
  usPassword: string;
  usPasswordSalt: string;
  usType: number;
  usStatus: number;
  usHeadImgUrl: string;
  usEmail: string;
  usDesc: string;
  usPhone: string;
  usAddress: string;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

const usStatus = {
  0: {text: '正常', status: 'Success',},
  1: {text: '冻结', status: 'Error',}
}

const usType = [
  {label: '公司', value: 0,},
  {label: '城市', value: 1,},
  {label: '店铺', value: 2,},
]

export default () => {
  const access = useAccess()

  const [modalOpen, handleModalOpen] = useState(false);
  const [modalRoleOpen, handleRoleModalOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // const [currentRow, setCurrentRow] = useState<ProductType>();

  const columns: ProColumns<User>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: '用户ID', dataIndex: 'usId', valueType: 'digit'},
    {title: '用户编号', dataIndex: 'usUuid', valueType: 'text'},
    {title: '用户昵称', dataIndex: 'usNickName', valueType: 'text',},
    {title: '邮箱', dataIndex: 'usEmail', valueType: 'text',},
    {title: '电话', dataIndex: 'usPhone', valueType: 'text',},
    {title: '地址', dataIndex: 'usAddress', valueType: 'text',},
    {title: '描述', dataIndex: 'usDesc', valueType: 'text',},
    {title: '真实姓名', dataIndex: 'usRealName', valueType: 'text',},
    {title: '登录名', dataIndex: 'usLoginName', valueType: 'text'},
    {title: '密码', dataIndex: 'usPassword', valueType: 'text', hideInSearch: true,},
    {title: '密码加盐', dataIndex: 'usPasswordSalt', valueType: 'text', hideInSearch: true,},
    {title: '类型', dataIndex: 'usType', valueType: 'select', fieldProps: {options: usType,}},
    {title: '状态', dataIndex: 'usStatus', valueType: 'select', valueEnum: usStatus},
    {title: '头像', dataIndex: 'usHeadImgUrl', valueType: 'text', hideInSearch: true,},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Button
          key={'edit_' + record.usId} size="small" icon={<EditOutlined/>} type="primary"
          onClick={async () => {

            form.setFieldsValue({...record});
            handleModalOpen(true);
          }}
        />,
        <Button
          key={'editrole_' + record.usId} size="small" icon={<TeamOutlined/>} type="primary"
          onClick={async () => {

            handleRoleModalOpen(true)

            setTimeout(async () => {
              const r = await globalApi('/user/userRoles', {userId: record.usId})
              form.setFieldsValue({usId: record.usId, roleIds: r.data})
            })
          }}
        />,
      ],
      valueType: 'option',
    },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<User>
      columns={columns} actionRef={actionRef}
      search={{span: 4}}
      headerTitle={
        <Button
          key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
          handleModalOpen(true)
        }}/>
      }
      request={async (param) => globalLoadTableApiCode('/user/table', 'user:list:search', access, param)}
      rowKey={(record) => record.usId}
      columnsState={{
        defaultValue: {
          usPassword: {show: false},
          usPasswordSalt: {show: false},
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false}
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="500px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/user/saveOrUpdate', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="用户ID" name="usId" hidden/>
      <ProForm.Group>
        <ProFormText label="用户昵称" rules={[{required: true}]} name="usNickName"/>
        <ProFormText label="真实姓名" rules={[{required: true}]} name="usRealName"/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText label="邮箱" rules={[{required: true}]} name="usEmail"/>
        <ProFormText label="电话" rules={[{required: true}]} name="usPhone"/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText label="地址" rules={[{required: true}]} name="usAddress"/>
        <ProFormSelect label="类型" rules={[{required: true}]} name="usType" options={usType}/>
      </ProForm.Group>

      {form.getFieldValue("usId") ? "" : <ProForm.Group>
        <ProFormText label="登录名" rules={[{required: true}]} name="usLoginName"/>
        <ProFormText.Password label="登录密码" rules={[{required: true}]} name="usPassword" initialValue={"123456"}/>
      </ProForm.Group>}

      <ProFormTextArea label="描述" name="usDesc"/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalRoleOpen} onOpenChange={handleRoleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        // let success = await handleUserRole(value as User)
        let success = await handleGloblApi('/user/userRole', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="用户ID" name="usId" hidden/>
      <ProFormSelect
        label="角色" rules={[{required: true}]} name="roleIds"
        request={async () => {
          const rolesSelect = await globalApi('/user/roles', {})
          return rolesSelect.data
        }}
        fieldProps={{showSearch: true, mode: 'multiple'}}/>
    </ModalForm>

  </PageContainer>
}
